<?php

namespace App\Models;

use App\Entities\PermissionRole;
use App\Entities\RoleUser;
use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'permissions';

    protected $fillable = [
        'name',
        'icon',
        'route',
        'pid',
        'sort',
        'is_disabled',
        'is_menu'
    ];

    public function child()
    {
        return $this->hasMany(self::class,'pid','id')
            ->select('id', 'name', 'pid', 'route', 'icon')
            ->where('is_disabled', '=', 0)
            ->where('is_menu', '=', 1)
            ->orderBy('sort', 'desc')
            ->with(['child']);
    }

    /**
     * Get parent of current node.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(self::class, 'pid');
    }


    public static function buildMenus() {
        return self::query()
            ->with(['child'])
            ->select('id','name','pid','route', 'icon')
            ->where('pid', '=', 0)
            ->where('is_disabled', '=',1)
            ->orderBy('sort', 'desc')
            ->get()->toArray();
    }

    /**
     * Get options for Select field in form.
     *
     * @param \Closure|null $closure
     * @param string        $rootText
     *
     * @return array
     */
    public static function selectOptions(\Closure $closure = null, $rootText = '功能列表')
    {
        $options = (new static())->buildSelectOptions();
        return collect($options)->prepend($rootText, 0)->all();
    }


    protected function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '', $space = '&nbsp;')
    {
        $prefix = $prefix ?: '┝'.$space;
        $options = [];

        if (empty($nodes)) {
            $nodes = Menu::orderBy('pid', 'asc')->orderBy('sort', 'desc')->get()->toArray();
        }

        foreach ($nodes as $index => $node) {
            if ($node['pid'] == $parentId) {
                $node['name'] = $prefix.$space.$node['name'];

                $childrenPrefix = str_replace('┝', str_repeat($space, 6), $prefix).'┝'.str_replace(['┝', $space], '', $prefix);

                $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $childrenPrefix);

                $options[$node[$this->getKeyName()]] = $node['name'];

                if ($children) {
                    $options += $children;
                }
            }
        }

        return $options;
    }


    public static function buildPermissionMenus($userId, $isSuper=false) {
        if($isSuper) {
            return self::query()
                ->with(['child'])
                ->select('id', 'name', 'pid', 'route', 'icon')
                ->where('pid', '=', 0)
                ->where('is_menu', '=', 1)
                ->where('is_disabled', '=', 0)
                ->orderBy('sort', 'desc')
                ->get()->toArray();
        }


        $role_ids = RoleUser::where('user_id', $userId)->pluck('role_id');
        $permission_ids = PermissionRole::whereIn('role_id', $role_ids)
            ->pluck('permission_id');

        return self::tree(self::query()->whereIn('id', $permission_ids)
            ->where('is_menu', '=', 1)
            ->where('is_disabled', '=', 0)
            ->orderBy('sort', 'desc')
            ->get());
    }


    /**
     * 获取权限树结构
     **/
    public static function tree($collection, $pid = 0)
    {
        $recurrence = function($recurrence, $pid) use($collection) {
            return $collection->where('pid', $pid)
                ->values()
                ->map(function($item) use ($recurrence, $collection) {
                    $data = [
                        'id' => $item['id'],
                        'pid' => $item['pid'],
                        'name' => $item['name'],
                        'route' => $item['route'] ? url($item['route']) : '',
                        'icon' => $item['icon'],
                    ];
                    if ($collection->where('pid', $item['id'])->isEmpty()) {
                        return $data;
                    }
                    $data['child'] = $recurrence($recurrence, $item['id']);
                    return $data;
                })->toArray();
        };
        return $recurrence($recurrence, $pid);
    }
}
